<template>
  <a-card class="tree-card" :title="title" :body-style="{ padding: '0px 10px 10px 10px' }">
    <div class="tree-container border">
      <!-- 树组件 -->
      <a-spin :loading="loading" style="width: 100%; height: auto" tip="加载中...">
        <a-tree ref="treeRef" v-model:selected-keys="selectedKeys" :data="treeData" @select="handleSelect" :fieldNames="fieldNames">
          <template #icon="{ node }">
            <icon-storage v-if="node.isGroup === 1" />
            <icon-thunderbolt v-else />
          </template>
        </a-tree>
      </a-spin>
    </div>
  </a-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { TreeInstance } from '@arco-design/web-vue';
import useLoading from '../../utils/loading';
import { listFusionGroup } from '../../apis/datamonitor';

// 加载状态管理
const { loading, setLoading } = useLoading(true);

// 接收父组件传递的属性
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  needCheck: {
    type: Boolean,
    default: true
  }
});

// 发送事件给父组件
const emit = defineEmits(['onChange']);

// 树实例引用
const treeRef = ref<TreeInstance>();

// 选中的节点键
const selectedKeys = ref<string[]>([]);

// 树数据
const treeData = ref<any>([]);

// 树字段映射
const fieldNames = ref({
  key: 'deviceSn',
  title: 'deviceName',
  children: 'children'
});

/**
 * 处理树节点选择
 */
const handleSelect = (node: any, data: any) => {
  console.log('节点选择事件:', selectedKeys.value, data);

  if (data.selectedNodes && data.selectedNodes.length === 1) {
    const info = data.selectedNodes[0];
    if (info.isGroup === 1) {
      // 如果是组节点，清空选中
      selectedKeys.value = [];
    } else {
      // 如果是设备节点，触发变更事件
      handleChange();
    }
  }
};

/**
 * 触发变更事件
 */
const handleChange = () => {
  const params = {
    deviceSn: selectedKeys.value.length > 0 ? selectedKeys.value[0] : '',
    deviceSns: []
  };

  console.log('设备列表变更:', params);
  emit('onChange', params);
};

/**
 * 查找第一个非组节点
 */
function findFirstNonGroup(data: any[]): any | null {
  for (const item of data) {
    if (item.isGroup === 0) {
      return item;
    } else if (item.children) {
      const result = findFirstNonGroup(item.children);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

/**
 * 加载树数据
 */
const fetchTreeData = async () => {
  setLoading(true);

  try {
    const params = {
      stationType: 2
    };

    const res = await listFusionGroup(params);
    console.log('设备列表请求结果:', res);

    if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
      treeData.value = res.data.data;

      if (props.needCheck) {
        const firstNonGroup = findFirstNonGroup(res.data.data);
        if (firstNonGroup) {
          selectedKeys.value.push(firstNonGroup.deviceSn);
        }
      }
    }
  } catch (error) {
    console.error('加载设备列表失败:', error);
  } finally {
    setLoading(false);
  }
};

// 组件挂载时加载树数据
onMounted(async () => {
  await fetchTreeData();
  // 展开所有节点
  treeRef.value?.expandAll(true);
  // 如果需要选中，触发变更事件
  if (props.needCheck && selectedKeys.value.length > 0) {
    handleChange();
  }
});
</script>

<style lang="less" scoped>
.tree-card {
  .tree-container {
    border-radius: 2px;
  }
}

.border {
  border: 1px solid var(--color-neutral-4);
}
</style>